package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

public class UserInputControl {	
	public static String getStrInput(String description, String regEX) throws IOException {
		System.out.print(description);
		System.out.print(UserInputControl.getTermintateStr());
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String input = in.readLine();
		if (Pattern.matches(regEX, input)) {
			return input;
		} else if (!input.equals("-1")) {
			return UserInputControl.getStrInput(description, regEX);
		}
		return null;
	}

	public static int getIntInput(String description, String digitsRange) throws IOException {
		System.out.print(description);
		System.out.print(UserInputControl.getTermintateStr());
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String input = in.readLine();
		if (Pattern.matches("[0-9]{" + digitsRange + "}", input)) {
			return Integer.parseInt(input);
		} else if (!input.equals("-1")) {
			return UserInputControl.getIntInput(description, digitsRange);
		}
		return 0;
	}

	public static Date getDateInput(String description) throws IOException {
		System.out.println(description);
		System.out.print(UserInputControl.getTermintateStr());
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
		String input = in.readLine();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
		boolean isDone = true;
		Date d = null;
		try {
			d = formatter.parse(input);
		} catch (ParseException e) {
			isDone = false;
		}

		if (isDone) {
			return d;
		} else if (!input.equals("-1")) {
			return UserInputControl.getDateInput(description);
		}
		return null;
	}

	public static String getTermintateStr() {
		return "(Enter -1 to teminate.) ";
	}
}